package com.example.demo;

import com.alibaba.ocean.rawsdk.ApiExecutor;
import com.alibaba.ocean.rawsdk.client.entity.AuthorizationToken;
import com.alibaba.ocean.rawsdk.common.SDKResult;
import com.alibaba.trade.param.*;
import com.example.service.*;
import com.example.shiti.TradeInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;

@RestController
@CrossOrigin(origins = "*")
public class ALLController {

    private static final Logger logger = Logger.getLogger(ALLController.class.getName());
    private final String appKey = "3751877";
    private final String appSecret = "5eJGGnlEzs";
    private final String redisTokenKey = "accessToken";  // Redis 中存储 Token 的键名

    private final SearchService searchService;
    @Autowired
    private GetAllOrder getAllOrder;
    @Autowired
    public ALLController(SearchService searchService) {
        this.searchService = searchService;
    }
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping("/listsize")
    public Long generateOrderssize(@RequestParam(name = "status") String status,
                                      @RequestParam(name = "startDate") LocalDateTime startDate,
                                      @RequestParam(name = "endDate") LocalDateTime curDate){//订单状态
        ApiExecutor apiExecutor = new ApiExecutor("3751877", "5eJGGnlEzs");
        return searchService.countOrdersByStatusAndCreateTimeRange(Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),Date.from(curDate.atZone(ZoneId.systemDefault()).toInstant()),status);
    }
    //分页获取订单
    @GetMapping("/list")
    public AlibabaAscpTradeSellerViewGetListResult generateOrders(
            @RequestParam(defaultValue = "1") int page,  // 前端未传递时默认为1
            @RequestParam(defaultValue = "20") int pageSize,  // 前端未传递时默认为20
            @RequestParam(name = "startDate") LocalDateTime startDate,
            @RequestParam(name = "endDate") LocalDateTime curDate,
            @RequestParam(name = "orderID") String orderID,//订单号
            @RequestParam(name = "buyer") String buyer,//买家电话姓名
            @RequestParam(name = "productInfo") String productInfo,//商品信息
            @RequestParam(name = "sort") String sort,//正反序
            @RequestParam(name = "status") String status,//订单状态
            @RequestParam(name = "direction") String direction//排序列
    ) {
        if (startDate.isBefore(LocalDateTime.now().minusMonths(3))) {
            startDate = LocalDateTime.now().minusMonths(3);
        }
        if (curDate.isAfter(LocalDateTime.now())) {
            curDate = LocalDateTime.now();
        }
        Sort sort1 = null;
        if(sort.equals("1")){
            Sort.by(Sort.Direction.ASC, direction);//正序
        }else{
            Sort.by(Sort.Direction.DESC, direction);
        }
        String Key = null;
        String value = null;
        List<TradeInfo> tradeInfoList = getAllOrder.GetAllTradeInfoMysql(Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant()),Date.from(curDate.atZone(ZoneId.systemDefault()).toInstant()),sort1,Key,value,status);
        List<AlibabaAscpTradeModelTradeInfo> skuInfosList = new ArrayList<>();
        for (TradeInfo t : tradeInfoList){
            skuInfosList.add(TradeInfoToAlibabaAscpTradeModelTradeInfoConverter.convert(t));
        }
        AlibabaAscpTradeSellerViewGetListResult result = new AlibabaAscpTradeSellerViewGetListResult();
        result.setResult(skuInfosList.toArray(new AlibabaAscpTradeModelTradeInfo[0]));
        return result;
//        int maxPageSize = 20;
//        ApiExecutor apiExecutor = new ApiExecutor("3751877", "5eJGGnlEzs");
//        AlibabaAscpTradeSellerViewGetListParam param = new AlibabaAscpTradeSellerViewGetListParam();
//        if(status.equals("waitsellersend")){
//            param.setOrderStatus("waitsellersend");
//        }
//        param.setPage(page);
//        Map<String,AlibabaAscpTradeModelTradeInfo> set = new HashMap<>();
//        int star = ((page-1)*pageSize)/20+1;
//        int n = pageSize/20;
//        if(orderID!=null&&orderID!=""){//根据订单号查询
//            AlibabaAscpTradeSellerViewGetParam param1 = new AlibabaAscpTradeSellerViewGetParam();
//            param1.setOrderId(orderID);
//            SDKResult<AlibabaAscpTradeSellerViewGetResult> sdkResult1 = apiExecutor.execute(param1, redisTemplate.opsForValue().get(redisTokenKey));
//            if(sdkResult1!=null&&sdkResult1.getResult().getResult()!=null){
//                set.put(sdkResult1.getResult().getResult().getBaseInfo().getId(),sdkResult1.getResult().getResult());
//                result.setResult(set.values().toArray(new AlibabaAscpTradeModelTradeInfo[0]));
//            }
//            return result;
//        }
//        if(buyer!=null&&buyer!=""){//根据收货人姓名电话查询
//            AlibabaAscpSoldOrderIdGetListParam param1 = new AlibabaAscpSoldOrderIdGetListParam();
//            param1.setPageNo(page);
//            param1.setPageSize(pageSize);
//            param1.setName(buyer);
//            SDKResult<AlibabaAscpSoldOrderIdGetListResult> sdkResult1 = apiExecutor.execute(param1, redisTemplate.opsForValue().get(redisTokenKey));
//            ComAlibabaCbuPanamaOrderClientModelPanamaOrderOpenModel[] a = sdkResult1.getResult().getResult().getResult();
//            for (ComAlibabaCbuPanamaOrderClientModelPanamaOrderOpenModel b:a) {
//                AlibabaAscpTradeSellerViewGetParam param2 = new AlibabaAscpTradeSellerViewGetParam();
//                param2.setOrderId(String.valueOf(b.getOrderId()));
//                SDKResult<AlibabaAscpTradeSellerViewGetResult> sdkResult2 = apiExecutor.execute(param2, redisTemplate.opsForValue().get(redisTokenKey));
//                if(sdkResult2!=null&&sdkResult2.getResult().getResult()!=null){
//                    set.put(sdkResult2.getResult().getResult().getBaseInfo().getId(),sdkResult2.getResult().getResult());
//                }
//            }
//            param1.setName("");
//            param1.setMobilephone(buyer);
//            result.setResult(set.values().toArray(new AlibabaAscpTradeModelTradeInfo[0]));
//            sdkResult1 = apiExecutor.execute(param1, redisTemplate.opsForValue().get(redisTokenKey));
//            ComAlibabaCbuPanamaOrderClientModelPanamaOrderOpenModel[] c = sdkResult1.getResult().getResult().getResult();
//            for (ComAlibabaCbuPanamaOrderClientModelPanamaOrderOpenModel b:c) {
//                AlibabaAscpTradeSellerViewGetParam param2 = new AlibabaAscpTradeSellerViewGetParam();
//                param2.setOrderId(String.valueOf(b.getOrderId()));
//                SDKResult<AlibabaAscpTradeSellerViewGetResult> sdkResult2 = apiExecutor.execute(param2, redisTemplate.opsForValue().get(redisTokenKey));
//                if(sdkResult2!=null&&sdkResult2.getResult().getResult()!=null){
//                    set.put(sdkResult2.getResult().getResult().getBaseInfo().getId(),sdkResult2.getResult().getResult());
//                }
//            }
//            result.setResult(set.values().toArray(new AlibabaAscpTradeModelTradeInfo[0]));
//            return result;
//        }
//        for (int i = 0; i <= n; i++) {
//            param.setPageSize(20);
//            param.setPage(star);
//            SDKResult<AlibabaAscpTradeSellerViewGetListResult> sdkResult = apiExecutor.execute(param, redisTemplate.opsForValue().get(redisTokenKey));
//            AlibabaAscpTradeModelTradeInfo[] array = sdkResult.getResult().getResult();
//            if (array == null){
//                break;
//            }
//            for (AlibabaAscpTradeModelTradeInfo a:array) {
//                if(set.size()<pageSize){
//                    if (productInfo!=null&&productInfo!="") {//根据商品信息查询
//                        AlibabaAscpTradeModelProductItemInfo[] ItemInfo = a.getProductItems();
//                        for(AlibabaAscpTradeModelProductItemInfo Io : ItemInfo){
//                            String s = Io.getProductID()+Io.getSkuID()+Io.getName()+Io.getSkuInfos()[0].getName()+Io.getSkuInfos()[0].getValue();
//                            if((String.valueOf(Io.getProductID())+String.valueOf(Io.getSkuID())+Io.getName()+Io.getSkuInfos()[0].getName()+Io.getSkuInfos()[0].getValue()).contains(productInfo)){
//                                if((a.getBaseInfo().getStatus()).equals(status)){
//                                    set.put(a.getBaseInfo().getId(),a);
//                                }
//                            }
//                        }
//                    }else {
//                        set.put(a.getBaseInfo().getId(),a);
//                    }
//                }else{
//                 break;
//                }
//            }
//            star++;
//        }
//        result.setResult(set.values().toArray(new AlibabaAscpTradeModelTradeInfo[0]));
//        SaveAllOrder order = new SaveAllOrder();
//        order.SaveOrder(result);
//
//        return result;
    }
    @GetMapping("/listOne")//获取单个订单真实信息
    public AlibabaAscpTradeSellerViewDecyrptRecevierResult generateOneOrders(@RequestParam(name = "id") String orderId,
    @RequestParam(name = "oaid") String oaid) {
        ApiExecutor apiExecutor = new ApiExecutor("3751877", "5eJGGnlEzs");
        AlibabaAscpTradeSellerViewDecyrptRecevierParam param = new AlibabaAscpTradeSellerViewDecyrptRecevierParam();
        param.setOrderId(orderId);
        param.setOaid(oaid);
        param.setScene("1002");
        SDKResult<AlibabaAscpTradeSellerViewDecyrptRecevierResult> sdkResult = apiExecutor.execute(param,redisTemplate.opsForValue().get(redisTokenKey));
        return sdkResult.getResult();
    }
    //登录获取token
    @GetMapping("/")
    public String ship_again_list(@RequestParam(name = "code") String code) {
        logger.info("收到的授权码: " + code);
        ApiExecutor apiExecutor = new ApiExecutor(appKey, appSecret);
        try {
            AuthorizationToken token = apiExecutor.getToken(code);
            String accessToken = token.getAccess_token();
            logger.info("获取的 access token: " + accessToken);
            redisTemplate.opsForValue().set(redisTokenKey, accessToken, token.getExpires_in(), TimeUnit.SECONDS);  // 将 Token 存储到 Redis 中，并设置过期时间
            return "启动成功";
        } catch (Exception e) {
            logger.log(Level.SEVERE, "获取令牌失败: ", e);
            return "启动失败";
        }
    }
    @GetMapping("/dataList")//根据时间获取订单
    public String getDataList(@RequestParam(name = "startDate") LocalDateTime startDate,
                              @RequestParam(name = "endDate") LocalDateTime curDate) {
        ApiExecutor apiExecutor = new ApiExecutor("3751877", "5eJGGnlEzs");
        AlibabaAscpTradeSellerViewGetListParam param = new AlibabaAscpTradeSellerViewGetListParam();
        param.setPageSize(20);
        TradeInfo LatestInfo = searchService.getLatestCreateTime();
        TradeInfo FirstInfo = searchService.getFirstCreateTime();
        Date startcomparisonDate = Date.from(startDate.atZone(ZoneId.systemDefault()).toInstant());
        Date curcomparisonDate = Date.from(curDate.atZone(ZoneId.systemDefault()).toInstant());
        if(FirstInfo==null){
            FirstInfo = new TradeInfo();
            FirstInfo.setCreateTime(new Date());
        }
        if(LatestInfo==null){
            LatestInfo = new TradeInfo();
            LatestInfo.setCreateTime(FirstInfo.getCreateTime());
        }
        if(startcomparisonDate.before(FirstInfo.getCreateTime())){
            if(LatestInfo.getCreateTime().before(curcomparisonDate)){
                param.setModifyStartTime(startcomparisonDate);
                param.setModifyEndTime(FirstInfo.getCreateTime());
                getAllOrder.GetAllOrderSave(param);
                param.setModifyStartTime(LatestInfo.getCreateTime());
                param.setModifyEndTime(curcomparisonDate);
                getAllOrder.GetAllOrderSave(param);
            }else{
                param.setModifyStartTime(startcomparisonDate);
                param.setModifyEndTime(FirstInfo.getCreateTime());
                getAllOrder.GetAllOrderSave(param);
            }
        }else if(LatestInfo.getCreateTime().before(curcomparisonDate)){
            param.setModifyStartTime(LatestInfo.getCreateTime());
            param.setModifyEndTime(curcomparisonDate);
            getAllOrder.GetAllOrderSave(param);
        }
        return "success";
    }
}
